<template>
  <div id="caclDatabase">
    <Breadcrumb content="数据源字典" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.keyWord" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getCalcDataBaseList" @search-click="getCalcDataBaseList"></vxe-input>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="getCalcDataBaseList" :loading="showLoading"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="add()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="calcDataBasetableBox">
            <vxe-table ref="caclDatabaseTableRef" :loading="showLoading" @current-change="currentChangeEvent" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="calcDataBaseList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="databaseCode" title="编码" width="60"></vxe-column>
              <vxe-column field="databaseName" title="名称"></vxe-column>
              <vxe-column field="databaseType" title="数据源类型">
                <template #default="{ row }">
                  {{ formatterType(row.databaseType) }}
                </template>
              </vxe-column>
              <vxe-column field="host" title="连接地址"> </vxe-column>
              <vxe-column field="port" title="端口"> </vxe-column>
              <vxe-column field="username" title="用户名"> </vxe-column>
              <vxe-column field="password" title="密码"> </vxe-column>
              <vxe-column field="dbName" title="数据库名称"> </vxe-column>
              <vxe-column field="remake" title="备注"> </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="40">
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <el-scrollbar style="height: 100%">
                <el-form ref="caclDatabaseFormRef" :model="caclDatabaseForm" :rules="caclDatabaseRules"  label-width="100px" class="form-input-m" inline-message>
                  <el-scrollbar style="height: 100%">
                    <el-form-item label="编码" prop="databaseCode">
                      <el-input v-model="caclDatabaseForm.databaseCode" placeholder="编码" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="名称" prop="databaseName"> <el-input v-model="caclDatabaseForm.databaseName" placeholder="名称" clearable></el-input> </el-form-item>
                    <el-form-item label="数据源类型" prop="databaseType">
                      <el-select v-model="caclDatabaseForm.databaseType" placeholder="数据源类型" style="width: 200px">
                        <el-option v-for="item in typeOptions" :key="item.value" :label="item.name" :value="item.value" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="连接地址" prop="host"> <el-input v-model="caclDatabaseForm.host" placeholder="连续剧地址" clearable></el-input> </el-form-item>
                    <el-form-item label="端口" prop="port"> <el-input v-model="caclDatabaseForm.port" placeholder="端口" clearable></el-input> </el-form-item>
                    <el-form-item label="用户名" prop="username"> <el-input v-model="caclDatabaseForm.username" placeholder="用户名" clearable></el-input> </el-form-item>
                    <el-form-item label="密码" prop="password"> <el-input v-model="caclDatabaseForm.password" placeholder="密码" clearable></el-input> </el-form-item>
                    <el-form-item label="数据库名称" prop="dbName"> <el-input v-model="caclDatabaseForm.dbName" placeholder="数据库名称" clearable></el-input> </el-form-item>
                    <el-form-item label="备注" prop="remake">
                      <el-input v-model="caclDatabaseForm.remake" :rows="6" type="textarea" placeholder="备注" clearable style="margin-right: 10px"></el-input>
                    </el-form-item>
                    <el-form-item class="form-footer">
                      <template #default>
                        <el-button type="primary" v-loading="saveLoading" @click="save()">保存</el-button>
                        <el-button type="primary" v-loading="testConnectionLoading" @click="testConnection()">测试连接</el-button>
                        <el-button type="default" @click="add()">重置</el-button>
                      </template>
                    </el-form-item>
                  </el-scrollbar>
                </el-form>
              </el-scrollbar>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息

// 定义变量区 ==========
let { proxy }: any = getCurrentInstance();
//根据关键字搜索
let searchForm = reactive({
  keyWord: ''
});
const calcDataBaseList = reactive([]); //表格数据
let showLoading = ref(false); //表格加载状态

//右侧基本信息表单数据
const caclDatabaseForm = reactive({
  id: '',
  databaseCode: '',
  databaseName: '',
  databaseType: 0,
  host: '',
  port: '',
  username: '',
  password: '',
  seq: 0,
  dbName: '',
  remake: ''
});
// 基本信息表单验证规则
let caclDatabaseRules = {
  databaseCode: [{ required: true, message: '请输入编码',trigger: 'blur'}],
  databaseName:[{ required: true, message: '请输入名称',trigger: 'blur'}],
  databaseType: [{ required: true, message: '请选择数据源类型',trigger: 'blur'}],
  host: [{ required: true, message: '请输入连接地址',trigger: 'blur'}],
  port: [{ required: true, message: '请输入端口号',trigger: 'blur'}],
  username: [{ required: true, message: '请输入用户名',trigger: 'blur'}],
  password: [{ required: true, message: '请输入密码',trigger: 'blur'}],
  dbName: [{ required: true, message: '请输入数据库名称',trigger: 'blur'}],
}


const typeOptions = reactive([
  {
    name: 'Oracle',
    value: 0
  },
  {
    name: 'SqlServer',
    value: 1
  },
  {
    name: 'DM',
    value: 2
  }
]);

let saveLoading = ref(false); //表单保存状态
let testConnectionLoading = ref(false); //表单保存状态
// 方法定义区 =====================================
onMounted(() => {
  getCalcDataBaseList();
});

// 获取左侧列表信息
function getCalcDataBaseList() {
  calcDataBaseList.length = 0;
  showLoading.value = true;
  const url = '/wk/calc/database/getDataBaseList';
  proxy.$http
    .get(url, { params: { keyWord: searchForm.keyWord } })
    .then((res: any) => {
      if (res.data) {
        calcDataBaseList.push(...res.data);
        currentChangeEvent({ row: calcDataBaseList[0] });
        const $xTable = proxy.$refs.caclDatabaseTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(calcDataBaseList[0]);
        }
        showLoading.value = false;
      }
    })
    .catch((err: any) => {
      showLoading.value = false;
      proxy.$alert(err, '提示');
    });
}
//点击表格当前行 数据变化
function currentChangeEvent(row: any) {
  add() ;// 重置 先清空右侧表单数据+校验错误
  Object.assign(caclDatabaseForm, row.row);
}

// 添加
function add() {
  const el: any = proxy.$refs.caclDatabaseFormRef;
  el.resetFields(); //重置该表单项，将其值重置为初始值，并移除校验结果
  Object.keys(caclDatabaseForm).forEach((key) => {
    switch (typeof caclDatabaseForm[key]) {
      case 'string':
        caclDatabaseForm[key] = '';
        break;
      case 'number':
        caclDatabaseForm[key] = 0;
        break;
    }
  });
}

// 保存
function save() {
  saveLoading.value = true;
  let url = '';
  if (caclDatabaseForm.id == '' || caclDatabaseForm.id == null || caclDatabaseForm.id == undefined) {
    url = '/wk/calc/database/addDataBase';
  } else {
    url = '/wk/calc/database/editDataBase';
  }
  const el: any = proxy.$refs.caclDatabaseFormRef;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      saveLoading.value = false;
      return false;
    }
    proxy.$http
      .post(url, caclDatabaseForm)
      .then((res: any) => {
        VxeMessage(res.status.msg, VxeNotifyType.success);
        getCalcDataBaseList();
        saveLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        saveLoading.value = false;
      });
  });
}

// 测试数据库连接
function testConnection() {
  testConnectionLoading.value = true;
  let url = '/wk/calc/database/testDatabaseConnection';
  const el: any = proxy.$refs.caclDatabaseFormRef;
  if (!el) return;
  el.validate((valid: any) => {
    if (!valid) {
      testConnectionLoading.value = false;
      return false;
    }
    proxy.$http
      .post(url, caclDatabaseForm)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
        testConnectionLoading.value = false;
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
        testConnectionLoading.value = false;
      });
  });
}
// 删除
function handleDelete() {
  const $xTable = proxy.$refs.caclDatabaseTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (selectRows.length <= 0) {
    VxeMessage('请先选中要删除的项', VxeNotifyType.warning);
    return;
  }
  proxy
    .$confirm('确定删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then((type) => {
      if (type === 'confirm') {
        let ids = selectRows.map((item) => item.id);
        const url = '/wk/calc/database/deleteDataBase';
        proxy.$http
          .post(url, ids)
          .then((res: any) => {
            if (res.status.code === 1) {
              VxeMessage('删除成功', VxeNotifyType.success);
              getCalcDataBaseList();
            } else {
              VxeMessage('删除失败', VxeNotifyType.error);
            }
          })
          .catch((err) => {
            VxeMessage(err.response.data.status.msg, VxeNotifyType.error);
          });
      }
    });
}
// 格式化左侧试卷表格状态
function formatterType(cellValue) {
  const item = typeOptions.find((item) => item.value === cellValue);
  return item ? item.name : '';
}
</script>

<style lang="scss" scoped>
#caclDatabase {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .calcDataBasetableBox {
        height: calc(100% - 40px);
      }
      .el-tabs {
        height: 100%;
      }
    }
  }
}
</style>
